package com.larry.mapreduce.mapjoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName MapReduceDemo
 * @Author larry
 * @Date 20:47 2021/11/9
 * @Description 01    小米
 * 02	华为
 * 03	格力
 * <p>
 * <p>
 * <p>
 * 1001	01	1
 * 1002	02	2
 * 1003	03	3
 * 1004	01	4
 * 1005	02	5
 * 1006	03	6
 **/
public class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    private Map<String, String> pdMap = new HashMap<>();
    private Text outV = new Text();

    //初始化
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //获取缓存文件，并放在集合中
        URI[] cacheFiles = context.getCacheFiles();

        FileSystem fs = FileSystem.get(new Configuration());
        FSDataInputStream fis = fs.open(new Path(cacheFiles[0]));

        //从流中获取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

        String line;
        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            //切割
            String[] split = line.split("\t");

            //赋值
            pdMap.put(split[0], split[1]);
        }

        //关流
        IOUtils.closeStream(reader);
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] split = line.split("\t");

        //获取pid
        String pname = pdMap.get(split[1]);

        //获取订单id和订单数量
        //封装
        outV.set(split[0] + "\t" + pname + "\t" + split[2]);

        context.write(outV, NullWritable.get());
    }
}
